package com.sanqing.iframe;

import com.sanqing.dao.Dao;
import com.sanqing.model.BookType;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BooktypeAddFrame extends JInternalFrame {
    private JTextField idField;
    private JTextField typeNameField;

    public BooktypeAddFrame() {
        super();
        final BorderLayout borderLayout = new BorderLayout();// 边框布局管理器
        getContentPane().setLayout(borderLayout);// 设置布局
        setIconifiable(true);                     // 设置窗体可最小化
        setClosable(true);                        // 设置窗体可关闭
        setTitle("图书类别添加");                 // 设置窗体标题
        setBounds(100, 100, 390, 180);           // 设置窗体位置和大小

        final JPanel mainPanel = new JPanel();    // 创建中心面板
        mainPanel.setBorder(new EmptyBorder(5, 10, 5, 10));// 设置边框
        final GridLayout gridLayout = new GridLayout(0, 2);// 创建表格布局管理器
        gridLayout.setVgap(5);                    // 设置组件之间垂直距离
        gridLayout.setHgap(5);                    // 设置组件之间平行距离
        mainPanel.setLayout(gridLayout);          // 设置布局
        getContentPane().add(mainPanel);          // 将中心面板加入到窗体

        final JLabel idLabel = new JLabel("类别编号：");
        mainPanel.add(idLabel);
        idField = new JTextField();
        mainPanel.add(idField);

        final JLabel typeNameLabel = new JLabel("类别名称：");
        mainPanel.add(typeNameLabel);
        typeNameField = new JTextField();
        mainPanel.add(typeNameField);

        final JPanel bottomPanel = new JPanel();
        bottomPanel.setBorder(new LineBorder(SystemColor.activeCaptionBorder, 1, false));
        getContentPane().add(bottomPanel, BorderLayout.SOUTH);
        final FlowLayout flowLayout = new FlowLayout();
        flowLayout.setVgap(2);
        flowLayout.setHgap(30);
        flowLayout.setAlignment(FlowLayout.RIGHT);
        bottomPanel.setLayout(flowLayout);

        JButton addButton = new JButton("添加");
        addButton.addActionListener(new AddBookTypeActionListener());
        bottomPanel.add(addButton);

        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        bottomPanel.add(closeButton);

        setVisible(true);
    }

    private class AddBookTypeActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 获取输入框中的值
            String idStr = idField.getText().trim();
            String typeName = typeNameField.getText().trim();

            // 输入验证
            if (idStr.isEmpty() || typeName.isEmpty()) {
                JOptionPane.showMessageDialog(BooktypeAddFrame.this, "所有字段都必须填写", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            int id;
            try {
                id = Integer.parseInt(idStr);
                if (id < 0) {
                    JOptionPane.showMessageDialog(BooktypeAddFrame.this, "类别编号必须为非负整数", "输入错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                if (id == 0) {
                    JOptionPane.showMessageDialog(BooktypeAddFrame.this, "类别编号不可为0", "输入错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(BooktypeAddFrame.this, "类别编号必须为整数", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 检查 id 和 typename 是否已经存在
            if (isIdExists(id)) {
                JOptionPane.showMessageDialog(BooktypeAddFrame.this, "该类别编号已存在，请重新输入", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (isTypeNameExists(typeName)) {
                JOptionPane.showMessageDialog(BooktypeAddFrame.this, "该类别名称已存在，请重新输入", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 创建 BookType 对象
            BookType bookType = new BookType();
            bookType.setId(id);
            bookType.setTypeName(typeName);

            // 调用 Dao 类的方法将图书类别信息插入数据库
            String sql = "INSERT INTO tb_booktype (id, typename) VALUES (" + id + ", '" + typeName + "')";
            int result = Dao.executeUpdate(sql);

            if (result > 0) {
                JOptionPane.showMessageDialog(BooktypeAddFrame.this, "图书类别添加成功", "添加成功", JOptionPane.INFORMATION_MESSAGE);
                // 清空输入框
                idField.setText("");
                typeNameField.setText("");
            } else {
                JOptionPane.showMessageDialog(BooktypeAddFrame.this, "图书类别添加失败", "添加失败", JOptionPane.ERROR_MESSAGE);
            }
        }

        private boolean isIdExists(int id) {
            String sql = "SELECT COUNT(*) FROM tb_booktype WHERE id = " + id;
            ResultSet rs = Dao.executeQuery(sql);
            try {
                if (rs.next()) {
                    return rs.getInt(1) > 0;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (rs != null) rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }

        private boolean isTypeNameExists(String typeName) {
            String sql = "SELECT COUNT(*) FROM tb_booktype WHERE typename = '" + typeName + "'";
            ResultSet rs = Dao.executeQuery(sql);
            try {
                if (rs.next()) {
                    return rs.getInt(1) > 0;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (rs != null) rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }
    }
}